package tech.dingxin.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * @author dingxin
 */
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final ChannelGroup group;

    public TextWebSocketFrameHandler(ChannelGroup group) {
        this.group = group;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            //如果该握手事件成功，则从ChannelPipeline中移除HttpRequestHandler
            ctx.pipeline().remove(HttpRequestHandler.class);
            //通知所有已连接WebSocket客户端
            group.writeAndFlush(new TextWebSocketFrame(
                    "Client: " + ctx.channel() + "joined"
            ));
            //将新的WebSocket Channal 增加到ChannelGroup中，以便它可以接收到所有的消息
            group.add(ctx.channel());
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        //增加消息的引用计数，并将它写道group中所有的客户端
        group.writeAndFlush(textWebSocketFrame.retain());
    }
}
